import { Middleware, Context } from '../core'
import { ViewGroup } from '../mapper/components'
import { ComponentFactory } from '../mapper'
import { Inject } from '..'
import { View } from '@tarojs/components'

/**
 * 解析页面
 */
export default class PageParserMiddleware implements Middleware {
  async process(context: Context, next: () => Promise<void>): Promise<void> {
    try {
      const pages = context.json.structData.pages
      context.tabInfo.forEach((tab, index) => {
        const page = pages.filter(p => tab.pageId == p.id)[0]
        const componentList = page.content.componentList
        const view = pageRender(componentList, context)
        // tab.component = view.render()
        tab.component = <View key={index}>{ view.render() }</View>
      })
      next()
    } catch (error) {
      throw new Error(`【页面解析出错】- ${error}`)
    }
  }
}

function pageRender(componentList: any[], context: Context): ViewGroup {
  const viewGroup = new ViewGroup()
  componentList.forEach(component => {
    viewGroup.addComponent(ComponentFactory.createComponent(component, context).render())
  })
  return viewGroup
}
